package net.stevechaloner.idea.ffs;

import net.stevechaloner.idea.ffs.model.src.Input;
import net.stevechaloner.idea.ffs.model.src.Search;
import net.stevechaloner.idea.ffs.model.xml.Param;
import net.stevechaloner.idea.ffs.model.xml.SearchPlugin;
import net.stevechaloner.idea.ffs.model.xml.Url;

import java.util.List;

/**
 * @author Steve Chaloner
 */
public class QueryFactory
{
    /**
     * Factory class.
     */
    private QueryFactory()
    {
    }

    /**
     *
     * @param term the search term
     * @param search the search provider
     * @return a query string for the search provider
     */
    public static String buildQuery(String term,
                                    Search search)
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(search.getAction().getValue());
        stringBuilder.append('?');

        List<Input> inputs = search.getInputs();
        for (Input input : inputs)
        {
            stringBuilder.append(input.getName());
            stringBuilder.append('=');
            if (input.getValue().getXmlAttribute() != null)
            {
                stringBuilder.append(input.getValue().getValue());
            }
            else
            {
                stringBuilder.append(term);
            }
            stringBuilder.append('&');
        }
        return stringBuilder.toString();
    }

    /**
     *
     * @param term the search term
     * @param search the search provider
     * @return a query string for the search provider
     */
    public static String buildQuery(String term,
                                    SearchPlugin search)
    {
        List<Url> urls = search.getUrls();
        Url url = null;
        for (Url u : urls)
        {
            if ("text/html".equals(u.getType().getValue()))
            {
                url = u;
                break;
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (url != null)
        {
            stringBuilder.append(url.getTemplate().getValue());
            stringBuilder.append('?');
            List<Param> params = url.getParams();
            for (Param param : params)
            {
                stringBuilder.append(param.getName()).append('=');
                if ("{searchTerms}".equals(param.getValue().getValue()))
                {
                    stringBuilder.append(term);
                }
                else
                {
                    stringBuilder.append(param.getValue().getValue());
                }
                stringBuilder.append('&');
            }

        }
        return stringBuilder.toString();
    }
}
